<template>
  <div class="p-2">
    <transition>
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="套餐名称" prop="packageName">
              <el-input v-model="queryParams.packageName" placeholder="请输入套餐名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="hover">
      <template slot="header">
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button v-hasPermi="['system:tenantPackage:add']" type="primary" plain icon="Plus"
              @click="handleAdd">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['system:tenantPackage:edit']" type="success" plain icon="Edit" :disabled="single"
              @click="handleUpdate()">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['system:tenantPackage:remove']" type="danger" plain icon="Delete"
              :disabled="multiple" @click="handleDelete()">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['system:tenantPackage:export']" type="warning" plain icon="Download"
              @click="handleExport">导出</el-button>
          </el-col>
          <right-toolbar v-model="showSearch" @query-table="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="tenantPackageList" @selection-change="handleSelectionChange" height="650">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column v-if="false" label="租户套餐id" align="center" prop="packageId" />
        <el-table-column label="套餐名称" align="center" prop="packageName" />
        <el-table-column label="备注" align="center" prop="remark" />
        <el-table-column label="状态" align="center" prop="status">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.status" active-value="0" inactive-value="1"
              @click="handleStatusChange(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-tooltip content="修改" placement="top">
              <el-button v-hasPermi="['system:tenantPackage:edit']" link type="text" icon="Edit"
                @click="handleUpdate(scope.row)">修改</el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button v-hasPermi="['system:tenantPackage:remove']" link type="text" icon="Delete"
                @click="handleDelete(scope.row)">删除</el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" v-model="queryParams.pageNum" :limit="queryParams.pageSize" :total="total"
        @pagination="getList" />
    </el-card>

    <el-dialog :visible.sync="dialog.visible" :title="dialog.title" width="500px" append-to-body>
      <el-form ref="tenantPackageFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="套餐名称" prop="packageName">
          <el-input v-model="form.packageName" placeholder="请输入套餐名称" />
        </el-form-item>
        <el-form-item label="关联菜单">
          <el-checkbox v-model="menuExpand" @change="handleCheckedTreeExpand($event, 'menu')">展开/折叠</el-checkbox>
          <el-checkbox v-model="menuNodeAll" @change="handleCheckedTreeNodeAll($event, 'menu')">全选/全不选 </el-checkbox>
          <el-checkbox v-model="form.menuCheckStrictly" @change="handleCheckedTreeConnect($event, 'menu')">父子联动
          </el-checkbox>
          <el-tree ref="menuTreeRef" class="tree-border" :data="menuOptions" show-checkbox node-key="id"
            :check-strictly="!form.menuCheckStrictly" empty-text="加载中，请稍候"
            :props="{ label: 'label', children: 'children' }"></el-tree>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template slot="footer">
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>


<script>
import {
  listTenantPackage,
  getTenantPackage,
  delTenantPackage,
  addTenantPackage,
  updateTenantPackage,
  changePackageStatus
} from '@/api/system/tenantPackage';
import { treeselect as menuTreeselect, tenantPackageMenuTreeselect } from '@/api/system/menu';
import to from 'await-to-js';

export default {
  name: 'TenantPackage',
  data() {
    return {
      formLabelWidth: "120px",
      tenantPackageList: [],
      buttonLoading: false,
      loading: true,
      showSearch: true,
      ids: [],
      single: true,
      multiple: true,
      total: 0,
      menuExpand: false,
      menuNodeAll: false,
      menuOptions: [],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        packageName: ''
      },
      form: {
        packageId: undefined,
        packageName: '',
        menuIds: '',
        remark: '',
        menuCheckStrictly: true
      },
      rules: {
        packageId: [{ required: true, message: '租户套餐id不能为空', trigger: 'blur' }],
        packageName: [{ required: true, message: '套餐名称不能为空', trigger: 'blur' }]
      },
      dialog: {
        visible: false,
        title: ''
      },
      animate: {
        searchAnimate: {
          enter: 'fadeIn',
          leave: 'fadeOut'
        }
      }
    };
  },
  methods: {
    getMenuTreeselect() {
      menuTreeselect().then((res) => {
        this.reset();
        this.menuOptions = res.data;
      });
    },
    getMenuAllCheckedKeys() {
      let checkedKeys = this.$refs.menuTreeRef.getCheckedKeys();
      let halfCheckedKeys = this.$refs.menuTreeRef.getHalfCheckedKeys();
      if (halfCheckedKeys) {
        checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
      }
      return checkedKeys;
    },
    async getPackageMenuTreeselect(packageId) {
      const res = await tenantPackageMenuTreeselect(packageId);
      this.menuOptions = res.data.menus;
      return Promise.resolve(res);
    },
    async getList() {
      this.loading = true;
      const res = await listTenantPackage(this.queryParams);
      this.tenantPackageList = res.rows;
      this.total = res.total;
      this.loading = false;
    },
    async handleStatusChange(row) {
      let text = row.status === '0' ? '启用' : '停用';
      const [err] = await to(this.$modal.confirm('确认要"' + text + '""' + row.packageName + '"套餐吗？'));
      if (err) {
        row.status = row.status === '0' ? '1' : '0';
      } else {
        await changePackageStatus(row.packageId, row.status);
        this.$modal.msgSuccess(text + '成功');
      }
    },
    cancel() {
      this.reset();
      this.dialog.visible = false;
    },
    reset() {
      this.$refs.menuTreeRef.setCheckedKeys([]);
      this.menuExpand = false;
      this.menuNodeAll = false;
      this.form = { packageId: undefined, packageName: '', menuIds: '', remark: '', menuCheckStrictly: true };
      this.$refs.tenantPackageFormRef.resetFields();
    },
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    resetQuery() {
      this.$refs.queryFormRef.resetFields();
      this.handleQuery();
    },
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.packageId);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    handleCheckedTreeExpand(value, type) {
      if (type == 'menu') {
        let treeList = this.menuOptions;
        for (let i = 0; i < treeList.length; i++) {
          if (this.$refs.menuTreeRef) {
            this.$refs.menuTreeRef.store.nodesMap[treeList[i].id].expanded = value;
          }
        }
      }
    },
    handleCheckedTreeNodeAll(value, type) {
      if (type == 'menu') {
        this.$refs.menuTreeRef.setCheckedNodes(value ? this.menuOptions : []);
      }
    },
    handleCheckedTreeConnect(value, type) {
      if (type == 'menu') {
        this.form.menuCheckStrictly = value;
      }
    },
    handleAdd() {
      this.dialog.visible = true;
      this.dialog.title = '添加租户套餐';
      this.getMenuTreeselect();
    },
    handleUpdate(row) {
      this.dialog.visible = true;
      this.dialog.title = '修改租户套餐';
      const _packageId = row?.packageId || this.ids[0];
      getTenantPackage(_packageId).then((res) => {
        this.reset();
        this.form = res.data;
        console.log(this.form)
      });
      this.getPackageMenuTreeselect(_packageId).then((res) => {
        res.data.checkedKeys.forEach(v => {
          this.$refs.menuTreeRef.setChecked(v, true, false);
        });
      });
    },
    submitForm() {
      this.$refs.tenantPackageFormRef.validate(async valid => {
        if (valid) {
          this.buttonLoading = true;
          this.form.menuIds = this.getMenuAllCheckedKeys();
          if (this.form.packageId != null) {
            await updateTenantPackage(this.form).finally(() => (this.buttonLoading = false));
          } else {
            await addTenantPackage(this.form).finally(() => (this.buttonLoading = false));
          }
          this.$modal.msgSuccess('操作成功');
          this.dialog.visible = false;
          await this.getList();
        }
      });
    },
    async handleDelete(row) {
      const _packageIds = row?.packageId || this.ids;
      await this.$modal.confirm('是否确认删除租户套餐编号为"' + _packageIds + '"的数据项？').finally(() => {
        this.loading = false;
      });
      await delTenantPackage(_packageIds);
      this.loading = true;
      await this.getList();
      this.$modal.msgSuccess('删除成功');
    },
    handleExport() {
      this.download(
        'system/tenantPackage/export',
        {
          ...this.queryParams
        },
        `tenantPackage_${new Date().getTime()}.xlsx`
      );
    }
  },
  mounted() {
    this.getList();
  }
};
</script>
